package rpc

import (
	"sync/atomic"

	"gitee.com/ameise84/e3dcs/internal/log"
	"gitee.com/ameise84/e3dcs/internal/message"
	"gitee.com/ameise84/e3net"
)

type RpcConn struct {
	raw      *rawContext
	tag      e3net.Tag
	isActive atomic.Bool
}

func (ts *RpcConn) Send(msg *message.Message) error {
	return ts.raw.Send(msg)
}

func TakeRpcConn(tag e3net.Tag, addr string) (*RpcConn, error) {
	ctx := takeRawContext()
	proxy := &RpcConn{
		raw: ctx,
	}
	_, err := _gService.agt.ConnectSync(tag, proxy.raw, addr)
	if err != nil {
		return nil, err
	}
	proxy.isActive.Store(true)
	log.GetLogger().Trace("take proxy rpc").Object(proxy.raw).Println()
	return proxy, nil
}

func FreeRpcConn(proxy *RpcConn) {
	log.GetLogger().Trace("free proxy rpc success").Object(proxy.raw).Println()
	if proxy.isActive.CompareAndSwap(false, true) {
		_ = proxy.raw.c.Close()
		freeRawContext(proxy.raw)
		proxy.raw = nil
	}
}
